<template>
  <!--模态窗 单行-->
  <transition
    name="custom-classes-transition"
    enter-active-class="animated fadeInDown"
    leave-active-class="animated fadeOutUp"
  >
    <div class="modal-ctrl-body" v-show="RevModalObj.isShow">
      <div class="modal-ctrl-main odd-row-ctrl">
        <div class="modal-title">
          <p>修改数据内容</p>
        </div>
        <div class="modal-ctrl-content">
          <div class="modal-row">
            <div class="modal-form-key f-l indispensable">
              逻辑名称：
            </div>
            <input type="text" maxlength="16"
                   placeholder="最长16个字符"
                   v-model="AddDataModal.name"
                   :disabled="RevModalObj.type == 'detail'"
                   class="modal-text f-l">
          </div>
          <div class="modal-row">
            <div class="modal-form-key f-l indispensable">
              逻辑源：
            </div>
            <select v-model="datasourceSelectedValue"
                    :disabled="RevModalObj.type == 'detail'"
                    :class="{'disabled-bg-color':RevModalObj.type == 'detail'}"
                    @change="selectFn">
              <option value="-1">请选择</option>
              <option v-for=" optionItem in filterData"
                      :value="optionItem.value+'_'+optionItem.type">
                {{optionItem.key}}
              </option>
            </select>
          </div>

          <div class="modal-row even-row-item clearfloat" v-show="sourceType != constSourceType">
            <div class="modal-form-key f-l indispensable">
              逻辑值：
            </div>
            <textarea type="text"
                      v-model="AddDataModal.logic"
                      :disabled="RevModalObj.type == 'detail'"
                      class="modal-text textarea f-l">
            </textarea>
          </div>
          <div v-show="sourceType == constSourceType">
            <div class="modal-row even-row-item clearfloat">
              <div class="modal-form-key f-l indispensable">
                逻辑值：
              </div>
            </div>
            <div class="logicMongo" >
              <div class="modal-row">
                <div class="modal-form-key f-l indispensable">
                  collection：
                </div>
                <input type="text"
                       maxlength="100"
                       placeholder="最长100个字符"
                       v-model="mongoList.collection"
                       :disabled="RevModalObj.type == 'detail'"
                       class="modal-text f-l">
              </div>
              <div class="modal-row"
                   :class="{'modal-row-detail': RevModalObj.type == 'detail'}"
                   v-show="RevModalObj.type != 'detail' || index != (mongoList.oneList.length - 1)"
                   v-for="(oneItem, index) in mongoList.oneList">
                <span v-show="RevModalObj.type != 'detail'" class="span-add-tree f-l" @click="mongoListAdd('one')"></span>
                <span v-show="RevModalObj.type != 'detail'" class="span-delete-tree f-l" :disabled="index != 0" @click="mongoListDelete('one', index)"></span>
                <input type="text"
                       maxlength="100"
                       placeholder="属性名"
                       :disabled="RevModalObj.type == 'detail'"
                       v-model="oneItem.key"
                       class="modal-text collection-value f-l">
                <select :disabled="RevModalObj.type == 'detail'"
                        :class="{'disabled-bg-color':RevModalObj.type == 'detail'}"
                        v-model="oneItem.type">
                  <option v-for=" optionItem in equalsList"
                          :value="optionItem.value">
                    {{optionItem.key}}
                  </option>
                </select>
                <input type="text"
                       maxlength="200"
                       placeholder="属性值"
                       :disabled="RevModalObj.type == 'detail'"
                       v-model="oneItem.value"
                       class="modal-text collection-key f-l">
              </div>
              <div class="modal-row"
                   :class="{'modal-row-detail': RevModalObj.type == 'detail'}"
                   v-show="RevModalObj.type != 'detail' || index != (mongoList.twoList.length - 1)"
                   v-for="(twoItem, index) in mongoList.twoList">
                <span class="span-add-tree f-l"
                      v-show="RevModalObj.type != 'detail'"
                      @click="mongoListAdd('two')"></span>
                <span class="span-delete-tree f-l"
                      :disabled="index != 0"
                      v-show="RevModalObj.type != 'detail'"
                      @click="mongoListDelete('two', index)"></span>
                <input type="text"
                       maxlength="200"
                       placeholder="属性值"
                       v-model="twoItem.value1"
                       :disabled="RevModalObj.type == 'detail'"
                       class="modal-text collection-key collection-two f-l">
                <select :disabled="RevModalObj.type == 'detail'"
                        :class="{'disabled-bg-color':RevModalObj.type == 'detail'}"
                        v-model="twoItem.type1">
                  <option v-for=" optionItem in equalsListTwoOne"
                          :value="optionItem.value">
                    {{optionItem.key}}
                  </option>
                </select>
                <input type="text" maxlength="100"
                       placeholder="属性名"
                       v-model="twoItem.key"
                       :disabled="RevModalObj.type == 'detail'"
                       class="modal-text collection-value collection-two-key f-l">
                <select :disabled="RevModalObj.type == 'detail'"
                        :class="{'disabled-bg-color':RevModalObj.type == 'detail'}"
                        v-model="twoItem.type2">
                  <option v-for=" optionItem in equalsListTwoTwo"
                          :value="optionItem.value">
                    {{optionItem.key}}
                  </option>
                </select>
                <input type="text"
                       maxlength="200"
                       placeholder="属性值"
                       v-model="twoItem.value2"
                       :disabled="RevModalObj.type == 'detail'"
                       class="modal-text collection-two collection-key f-l">
              </div>
            </div>
          </div>
          <div v-show="RevModalObj.type != 'detail'" class="modal-row">
            <div class="modal-form-key f-l ">
              返回结果：
            </div>
            <div disabled
                 class="modal-text result-data-content no-user-select f-l">
              {{result | resultFilter}}
            </div>
          </div>
        </div>
        <div class="btns text-r">
          <button type="button"
                  class="btn btn-info"
                  v-show="RevModalObj.type == 'update'"
                  @click="AddFn('test')">test</button>
          <button type="button"
                  class="btn btn-info"
                  v-show="RevModalObj.type == 'update'"
                  @click="AddFn('add')">保存</button>
          <button type="button" class="btn btn-default" @click="closeRoleModal">取消</button>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
  export default {
    name: "RevDefModel",
    props:["RevModalObj"],
    data(){
      return{
        AddDataModal:{
          name: '', // 逻辑名称
          datasourceId: '', // 数据源
          logic: '', // 逻辑值
          id: '', // 逻辑值
        },
        filterData: [],
        constSourceType: '3', // 默认mongoDB选中项的type
        sourceType: '', // 选中项的type
        equalsList: [
          {key: '=', value: '$eq'},
          {key: '<', value: '$lt'},
          {key: '<=', value: '$lte'},
          {key: '>', value: '$gt'},
          {key: '>=', value: '$gte'},
          {key: '!=', value: '$ne'}
        ],
        equalsListTwoOne: [
          {key: '<', value: '$gt'},
          {key: '<=', value: '$gte'},
        ],
        equalsListTwoTwo: [
          {key: '<', value: '$lt'},
          {key: '<=', value: '$lte'},
        ],
        mongoList: {
          collection: '',
          oneList: [],
          twoList: []
        },
        result: -1,
        datasourceSelectedValue: ''
      }
    },
    mounted(){
      this.init()
    },
    computed: {

    },
    methods:{
      // 弹窗显示加载初始化表单数据
      getInitData () {
        this.AddDataModal.id = this.RevModalObj.id
        this.$axios.get(this.Beacon + '/join/showUpdate/' + this.RevModalObj.id).then(res => {
         // debugger
          let self = this
          this.AddDataModal.name = res.data.content.name
          this.AddDataModal.datasourceId = res.data.content.datasourceId
          this.sourceType = this.filterDataTypeFn(res.data.content.datasourceId)
          this.datasourceSelectedValue = res.data.content.datasourceId + '_' + this.sourceType
          this.AddDataModal.logic = res.data.content.logic
          if (this.sourceType == this.constSourceType) {
            let obj = JSON.parse(this.AddDataModal.logic)
            for(let prop in obj) {
              this.mongoList.collection = prop
            }
            for(let prop2 in obj[this.mongoList.collection]) {
              let _len = 0
              let _str = {
                value1: '',
                value2: '',
                type1: '',
                type2: '',
              }
              for (let prop3 in obj[self.mongoList.collection][prop2]) {
                _len += 1
                let _strValue = 'value'+_len
                let _strType = 'type'+_len
                _str[_strValue] = obj[self.mongoList.collection][prop2][prop3]
                _str[_strType] = prop3
              }
              if (_len == 1){
                self.mongoList.oneList.push(
                  {
                    key: prop2,
                    type: _str.type1,
                    value: _str.value1
                  }
                )
              } else if (_len == 2) {
                self.mongoList.twoList.push(
                  {
                    value1: _str.value1,
                    type1: _str.type1,
                    key: prop2,
                    type2: _str.type2,
                    value2: _str.value2
                  }
                )
              }
            }
            this.mongoList.oneList.push(
              {
                key: '',
                type: '$eq',
                value: ''
              }
            )
            this.mongoList.twoList.push(
              {
                value1: '',
                type1: '$gt',
                key: '',
                type2: '$lt',
                value2: ''
              }
            )
          }
        })
      },
      // 通过id匹配数据源名称type
      filterDataTypeFn (datasourceId) {
        let data = this.filterData.filter(item => {
          if (item.value == datasourceId) {
            return true
          }
        })
        if (data.length > 0 && data[0].key) {
          return data[0].type
        } else {
          return '数据有问题'
        }
      },
      init() {
        this.getDataSourceType()
      },
      // 获取逻辑源
      getDataSourceType () {
        let _url = this.Beacon + '/datasource/queryList?size=0'
        this.$axios.get(_url).then(res => {
          let data = []
          res.data.content.records.map(item => {
            data.push({
              key: item.datasourceName,
              value: item.id,
              type: item.datasourceType
            })
          })
          this.filterData = data
        }).catch(err => {
          console.log(err, '数据源类型')
        })
      },
      selectFn (ele) {
        let list = ele.target.value.split('_')
        this.AddDataModal.datasourceId = list[0]
        this.sourceType = list[1]
        if (this.sourceType == this.constSourceType) {
          this.mongoList = {
            collection: '',
            oneList: [
              {
                key: '',
                type: '$eq',
                value: ''
              }
            ],
            twoList: [
              {
                value1: '',
                type1: '$gt',
                key: '',
                type2: '$lt',
                value2: ''
              }
            ]
          }
        } else {
          this.AddDataModal.logic = ''
        }
      },
      // mogoList Add
      mongoListAdd (str) {
        if (str === 'one') {
          this.mongoList.oneList.push(
            {
              key: '',
              type: '$eq',
              value: ''
            }
          )
        } else if (str === 'two') {
          this.mongoList.twoList.push(
            {
              value1: '',
              type1: '$gt',
              key: '',
              type2: '$lt',
              value2: ''
            }
          )
        }
      },
      // mogoList Delete
      mongoListDelete (str, index) {
        if (str === 'one' && index != 0) {
          this.mongoList.oneList.splice(index, 1)
        } else if (str === 'two' && index != 0) {
          this.mongoList.twoList.splice(index, 1)
        }
      },
      //清除缓存
      clearData(){
        this.AddDataModal = {
          name: '', // 逻辑名称
          datasourceId: '', // 数据源
          logic: '', // 逻辑值
        }
        this.sourceType = ''
        this.mongoList = {
          collection: '',
          oneList: [],
          twoList: []
        }
        this.result = -1
      },
      //关闭弹窗
      closeRoleModal(){
        this.clearData();
        this.$emit("closeModal");
      },
      // 弹窗确认按钮
      AddFn (str) {
        if (this.verifyForm.isNull(this.AddDataModal.name)) {
          this.s_alert('逻辑名称不能为空')
          return
        }
        if (this.verifyForm.isNull(this.AddDataModal.datasourceId)) {
          this.s_alert('逻辑源不能为空')
          return
        }
        if (str === 'add' && this.result != 1) {
          this.s_alert('请先点击测试按钮，确认测试成功')
          return
        }

          // mongo
          if (this.sourceType == this.constSourceType) {
            if (this.mongoList.collection.length > 0){
              let mongoLogic = {}
              let _collection = this.mongoList.collection
              mongoLogic[_collection] = {}
              this.mongoList.oneList.map(item => {
                let _objKey = item.key.toString()
                let _objType = item.type.toString()
                if (_objKey.length > 0 && _objType.length > 0) {
                  mongoLogic[_collection][_objKey] = {}
                  mongoLogic[_collection][_objKey][_objType] = item.value
                }
              })
              this.mongoList.twoList.map(item => {
                let _objKey = item.key.toString()
                let _objType1 = item.type1.toString()
                let _objType2 = item.type2.toString()
                if (_objKey.length > 0 && _objType1.length > 0 && _objType2.length > 0 && item.value1.length > 0 && item.value2.length > 0) {
                  mongoLogic[_collection][_objKey] = {}
                  mongoLogic[_collection][_objKey][_objType1] = item.value1
                  mongoLogic[_collection][_objKey][_objType2] = item.value2
                }
              })
              if (this.mongoList.oneList.length == 0 && this.mongoList.twoList.length == 0) {
                this.AddDataModal.logic = "{" + this.mongoList.collection+":"+null + "}"
              } else {
                this.AddDataModal.logic = JSON.stringify(mongoLogic)
              }
            } else {
              this.s_alert('collection不能为空')
              return
            }
          } else {
            if (this.verifyForm.isNull(this.AddDataModal.logic)) {
              this.s_alert('逻辑值不能为空')
              return
            }
          }
        if (str === 'add') {
          let _url = this.Beacon +
            '/join/saveOrUpdate'
          this.$axios.post(_url, this.AddDataModal).then(res => {
            if (res.data.success) {
              this.s_alert('修改成功')
              this.closeRoleModal()
            }
          }).catch(err => {
            console.log(err);
            this.s_alert('修改失败')
          })
        } else if (str === 'test') {
          let _url = this.Beacon +
            '/join/testResult'
          this.$axios.post(_url, this.AddDataModal).then(res => {
            if (res.data.success) {
              this.result = 1
            }
          }).catch(err => {
            this.result = 0
          })
        }
      },
    },
    filters: {
      resultFilter (val) {
        switch (val) {
          case 0:
            return '测试失败'
          case 1:
            return '测试成功'
          case -1:
            return '请先填写列表参数，然后点击test测试'
        }
      }
    },
    watch: {
      RevModalObj: {
        handler (val) {
          if (val.isShow) {
            this.getInitData()
            // debugger
          }
        },
        deep:true
      }
    }
  }
</script>

<style lang="less" scoped>
.modal-ctrl-body .modal-ctrl-main.odd-row-ctrl .logicMongo {
  width: 97%;
  margin-left: 3%;
  margin-top: -14px;
  .modal-text {
    &.collection-value, &.collection-key {
      width: 39%;
      &.collection-two {
        width: 21%;
      }
      &.collection-two-key {
        width: 22%;
      }
    }
  }
  select {
    float: left;
    width: 10%;
    margin: 0 2%;
  }
}
.result-data-content{
  line-height: 30px;
  background-color: #eeeeee;
  cursor: no-drop;
}
</style>
